import axios from 'axios'
import router from '../router/index'
import { Message } from 'view-design'

const http = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 3000,
  responseType: 'json'
})

const msg = []

http.interceptors.request.use(config => {
  msg.push(Message.loading({
    content: '加载中...',
    duration: 0
  }))
  config.headers['Authentication-Token'] = sessionStorage.getItem('token')
  return config
})

http.interceptors.response.use(res => {
  if (msg.length) setTimeout(msg.pop(), 0)
  if (res.status === 200) {
    if (res.data.code === 401) {
      Message.error({
        content: res.data.msg,
        duration: 1,
        onClose: () => router.replace('/login')
      })
    } else if (res.data.code === 402) Message.error('你当前没有权限访问该模块！')
    else if (res.data.code === 500) Message.error('服务器错误，请联系管理员')
    else if (res.data.code === 400) Message.error(res.data.msg)
    return res.data
  } else {
    Message.error('服务器错误，请联系管理员')
  }
}, err => {
  if (msg.length) setTimeout(msg.pop(), 0)
  Message.error(err)
})

export default http
